package org.bookie.init.tasks;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.apache.hivemind.ApplicationRuntimeException;
import org.apache.hivemind.Registry;
import org.bookie.init.InitTask;

public class JNDIDBCheck implements InitTask {

	public Properties execute(Registry reg) throws Exception {
		Properties prop = new Properties();
		Context ctx = new InitialContext();
		ctx = (Context) ctx.lookup("java:comp/env");
		DataSource ds = (DataSource) ctx.lookup("jdbc/BookieDB");
		if (ds == null) throw new ApplicationRuntimeException("Datasource is not found");
		prop.put("Database reference found", "OK");
		Connection connection = ds.getConnection();
		prop.put("Connection fetched from the DS", "OK");
		DatabaseMetaData md = connection.getMetaData();
		prop.put("Connection URl", md.getURL());
		prop.put("DB Driver", md.getDriverName() + " " + md.getDriverVersion());
		prop.put("DB Server", md.getDatabaseProductName() + " " + md.getDatabaseProductVersion());
		PreparedStatement statement = connection.prepareStatement("SELECT 1 + 5");
		statement.execute();
		statement.close();
		connection.close();
		prop.put("Connection initialization", "OK");
		return prop;
	}

	public String getTitle() {
		return "JNDI Database Reference";
	}

	public Properties check(Registry reg) throws Exception {
		Properties prop = new Properties();
		prop.setProperty("Database JNDI Name", "jdbc/BookieDB");
		return prop;
	}

}
